package fork.join.merge;

import java.util.concurrent.RecursiveAction;

/**
 * @author dycong
 * @date 2019/3/22 10:03
 */
public class MergeSortTask extends RecursiveAction {

    private static final int threshold = 100000;
    private static final long serialVersionUID = -3051595602943397888L;
    private final MergeSortWorker mergeSortWorker = new MergeSortWorker();

    private int[] data;

    private int left;
    private int right;

    public MergeSortTask(int[] array, int l, int r) {
        this.data = array;
        this.left = l;
        this.right = r;
    }

    @Override
    protected void compute() {
        if (right - left < threshold) {
            mergeSortWorker.sort(data, left, right);
        } else {
            int mid = left + (right - left) / 2;
            MergeSortTask l = new MergeSortTask(data, left, mid);
            MergeSortTask r = new MergeSortTask(data, mid + 1, right);

            invokeAll(l, r);

            mergeSortWorker.merge(data, left, mid, right);
        }
    }
}
